/*
 * Creater:     柿子
 * CreateDate:  2022/07/28
 * Describe：   电子病历引用
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Input, Button, Modal, message, Icon, Popconfirm, Divider } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

class EMRReference extends Component {
	constructor(props) {
		super(props);
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state = {
			userData,
			tempValue: undefined, // 主模板搜索条件
			mainLoading: false,
			mainTableData: [], // 主模板列表数据
			mainTableDataBackup: [], // 主模板列表备份数据
			mainRowID: '',
			mainRowData: {},
			mainElementLoading: false,
			mainElementTableData: [], // 主模板元素列表数据
			mainElementRowID: '',
			detailLoading: false,
			detailTableData: [],  // 明细模板列表数据
			elementSelectData: [], // 病历元素
			copyElementSelectData: [],
			modalTemRowID: '',
			modalTemRowData: {},
			visible: false,
			quoteTemVisible: false,
			modalTemplateTableData: [], // 弹窗模板列表数据
			copyModalTemplateTableData: [],
			modalElementTableData: [], // 弹窗元素列表数据
			copyModalElementTableData: []
		};

		this.staticColumns = [{
			title: '序号',
			dataIndex: 'key',
			width: '60px',
			align: "center",
		}, {
			title: '模板代码',
			dataIndex: 'code',
			align: "center",
			width: '120px',
		}, {
			title: '模板描述',
			dataIndex: 'descripts',
			align: "center",
		}];

		this.staticElementColumns = [{
			title: '元素代码',
			dataIndex: 'code',
			width: '150px',
			align: "center",
		}, {
			title: '元素名称',
			dataIndex: 'descripts',
			width: '200px',
			align: "center",
		}];

		this.staticElementModalColumns = [{
			title: '元素代码',
			dataIndex: 'code',
			width: '150px',
			align: "center",
		}, {
			title: '元素名称',
			dataIndex: 'descripts',
			width: '200px',
			align: "center",
		}, {
			title: 'filedID',
			dataIndex: 'internalCode',
			width: '150px',
			align: "center",
		}, {
			title: '注解',
			dataIndex: 'definition',
			width: '300px',
			align: "center",
		}];

		this.staticDetailColumns = [{
			title: '模板代码',
			dataIndex: 'tocode',
			align: "center",
			width: '150px',
		}, {
			title: '病历模板',
			dataIndex: 'todescripts',
			align: "center",
			width: '250px',
		}, {
			title: '元素代码',
			dataIndex: 'todataAttributesCode',
			align: "center",
			width: '150px',
		}, {
			title: '元素名称',
			dataIndex: 'todataAttributesDescripts',
			align: "center",
			width: '250px',
		}];
	}

	componentDidMount() {
		this.getMainTableData();
	}

	// 获取主病历模板数据
	getMainTableData = async () => {
		this.setState({ mainLoading: true });
		try {
			let { userData } = this.state;
			let data = {
				params: [{
					hospID: userData?.hospID || ''
				}],
			}
			let res = await React.$asyncPost(this, '06050032', data);
			let tableData = Util.addKeyValueToDataSource(res.result);
			for (var i = 0; i < tableData.length; i++) { // 增加过滤数据
				tableData[i].filterVal = (tableData[i]?.code || '') + '^' + (tableData[i]?.descripts || '');
			}
			this.setState({ mainTableData: tableData, mainTableDataBackup: tableData, modalTemplateTableData: tableData, copyModalTemplateTableData: tableData, mainLoading: false });
		} catch (error) {
			this.setState({ mainTableData: [], mainTableDataBackup: [], modalTemplateTableData: [], copyModalTemplateTableData: [], mainLoading: false });
		}
	}

	// 过滤主列表数据
	handleFilterMainTableData = () => {
		let { tempValue, mainTableDataBackup } = this.state;
		if (tempValue) {
			let newMainTableData = [];
			for (var i = 0; i < mainTableDataBackup.length; i++) {
				let currentCode = mainTableDataBackup[i]?.code || '';
				let currentDesc = mainTableDataBackup[i]?.descripts || '';
				if ((currentCode && currentCode.indexOf(tempValue) > -1) || (currentDesc && currentDesc.indexOf(tempValue) > -1)) {
					newMainTableData.push(mainTableDataBackup[i]);
				}
			}
			this.setState({ mainTableData: Util.addKeyValueToDataSource(newMainTableData) });
		} else {
			this.setState({ mainTableData: mainTableDataBackup });
		}
		this.handleClearData();
	}

	// 操作主模板列表行
	handleMainRowClick = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.mainRowID === '' || this.state.mainRowID !== record.templateID) {
					this.setState({ mainRowID: record.templateID, mainRowData: record, mainElementRowID: '', elementSelectData: [], detailTableData: [] }, () => {
						this.getElementSelectData();
						this.getDetailTableData('mainElementTableData', 'mainElementLoading');
					})
				} else {
					this.handleClearData();
				}
			}
		}
	}

	handleClearData = () => {
		this.setState({ mainRowID: '', mainRowData: {}, mainElementTableData: [], mainElementRowID: '', elementSelectData: [], detailTableData: [] });
	}

	// 根据病历模板获取病历元素
	getElementSelectData = async (recordDataIndex = 'mainRowData', dataIndex = 'elementSelectData') => {
		let { userData } = this.state;
		let data = {
			params: [{
				hospID: userData?.hospID || '',
				nationalCatalogueID: this.state[recordDataIndex]?.nationalCatalogueID || '',
			}],
		}
		let res = await React.$asyncPost(this, '06050033', data);
		let tableData = Util.addKeyValueToDataSource(res.result);
		for (var i = 0; i < tableData.length; i++) { // 增加过滤数据
			tableData[i].filterVal = (tableData[i]?.code || '') + '^' + (tableData[i]?.descripts || '') + '^' + (tableData[i]?.internalCode || '') + '^' + (tableData[i]?.definition || '')
		}
		if (dataIndex === 'elementSelectData') {
			this.state.copyElementSelectData = tableData;
		} else {
			this.state.copyModalElementTableData = tableData;
		}
		this.state[dataIndex] = tableData;
		this.setState({});
	}

	// 选中行操作
	handleMainRowClassName = (record) => {
		return record.templateID === this.state.mainRowID ? 'clickRowStyle' : '';
	}

	// 添加主模板元素
	handleAddMainElement = () => {
		const { copyElementSelectData } = this.state;
		this.setState({ elementSelectData: copyElementSelectData }, () => {
			this.modifyVisible(true);
		});
	}

	// 操作元素列表行
	handleMainElementRowClick = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.mainElementRowID === '' || this.state.mainElementRowID !== record.nationalDataID) {
					this.setState({ mainElementRowID: record.nationalDataID }, () => {
						this.getDetailTableData();
					})
				} else {
					this.setState({ mainElementRowID: '', detailTableData: [] });
				}
			}
		}
	}

	// 获取引用数据列表数据
	getDetailTableData = async (dataIndex = 'detailTableData', loadingIndex = 'detailLoading') => {
		this.state[loadingIndex] = true;
		this.setState({})
		try {
			let { userData, mainRowData, mainElementRowID } = this.state;
			let data = {
				params: [{
					hospID: userData?.hospID || '',
					nationalDataID: dataIndex === 'mainElementTableData' ? undefined : mainElementRowID,
					templateID: mainRowData?.templateID || '',
				}],
			}
			let res = await React.$asyncPost(this, '06050034', data);
			let tableData = res && res.result && Array.isArray(res.result) ? res.result : [];
			let firstToresult = tableData && tableData.length > 0 ? (tableData[0]?.toresult || []) : []
			if (dataIndex === 'mainElementTableData' && tableData && tableData.length > 0) { // 点击模板查询元素及引用数据时自动默认引用数据
				this.state['detailTableData'] = Util.addKeyValueToDataSource(firstToresult);
				this.state['mainElementRowID'] = tableData[0]?.nationalDataID || '';
			}
			if (dataIndex === 'detailTableData') {
				tableData = firstToresult;
			}
			this.state[dataIndex] = Util.addKeyValueToDataSource(tableData);
			this.state[loadingIndex] = false;
			this.setState({});
		} catch (error) {
			this.state[dataIndex] = [];
			this.state[loadingIndex] = false;
			this.setState({});
		}
	}

	// 选中行操作
	handleMainElementRowClassName = (record) => {
		return record.nationalDataID === this.state.mainElementRowID ? 'clickRowStyle' : '';
	}

	// 添加引用数据
	handleAddDetailElement = () => {
		const { copyModalTemplateTableData, copyModalElementTableData } = this.state;
		this.setState({ modalTemplateTableData: copyModalTemplateTableData, modalElementTableData: copyModalElementTableData }, () => {
			this.modifyVisible(true, 'quoteTemVisible');
		})
		let { detailRowData } = this.state;
		if (detailRowData && detailRowData.nationAttributeRelevanceID) {
			this.setState({ detailRowData: {}, modalTemRowID: '', modalTemRowData: {}, modalElementTableData: [], modalElementRowID: '' })
		}
	}

	// 表格数据选择
	handleRowSelectionChange = (selectedRowKeys, selectedRows) => {
		this.setState({
			selectedRowKeys,
			selectedRows
		});
	}

	// 修改弹窗状态
	modifyVisible = (flag, dataIndex = 'visible') => {
		this.state[dataIndex] = flag;
		this.setState({});
	}

	// 添加元素
	handleConfirm = () => {
		let { selectedRows } = this.state;
		if (selectedRows && selectedRows.length > 0) {
			this.setState({ mainElementTableData: selectedRows, mainElementRowID: selectedRows[0].nationalDataID, selectedRowKeys: [], selectedRows: [] }, () => {
				this.modifyVisible(false)
			})
		} else {
			message.error('请选择需要添加的数据')
		}
	}

	// 弹窗模板行数据选择
	handleModalTemRowClick = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.modalTemRowID === '' || this.state.modalTemRowID !== record.templateID) {
					this.setState({ modalTemRowID: record.templateID, modalTemRowData: record }, () => {
						this.getElementSelectData('modalTemRowData', 'modalElementTableData');
					})
				} else {
					this.setState({ modalTemRowID: '', modalTemRowData: {} })
				}
			}
		}
	}

	handleModalRowClassName = (record) => {
		return record.templateID === this.state.modalTemRowID ? 'clickRowStyle' : '';
	}

	handleModalElementRowClick = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.modalElementRowID === '' || this.state.modalElementRowID !== record.nationalDataID) {
					this.setState({ modalElementRowID: record.nationalDataID })
				} else {
					this.setState({ modalElementRowID: '' })
				}
			}
		}
	}

	handleModalElementRowClassName = (record) => {
		return record.nationalDataID === this.state.modalElementRowID ? 'clickRowStyle' : '';
	}

	// 确认引用模板
	handleQuoteConfirm = async () => {
		let { userData, mainRowData, mainElementRowID, modalTemRowData, modalElementRowID, detailRowData } = this.state;
		if (modalTemRowData && modalTemRowData.key && modalElementRowID) {
			let data = {
				params: [{
					hospID: userData?.hospID || '',
					nationAttributeRelevanceID: detailRowData?.nationAttributeRelevanceID || '',
					fromTemplateID: mainRowData?.templateID || '',
					fromdataAttributesID: mainElementRowID,
					toTemplateID: modalTemRowData?.templateID || '',
					todataAttributesID: modalElementRowID,
				}],
			}
			let res = await React.$asyncPost(this, '06050035', data);
			if (res.errorCode === '0') {
				message.success(res.errorMessage || '保存成功');
				this.setState({ modalTemRowID: '', modalTemRowData: {}, modalElementTableData: [], modalElementRowID: '' }, () => {
					this.modifyVisible(false, 'quoteTemVisible');
					this.getDetailTableData();
				})
			}
		} else {
			message.error('请选择需要模板/元素数据进行保存');
		}
	}

	// 修改引用数据
	handleCompile = record => {
		let { mainTableDataBackup } = this.state;
		let templateID = record?.toTemplateDr || '';
		let nationalCatalogueID = '';
		for (var i = 0; i < mainTableDataBackup.length; i++) {
			if (mainTableDataBackup[i].templateID === templateID) {
				nationalCatalogueID = mainTableDataBackup[i].nationalCatalogueID;
				break;
			}
		}
		this.modifyVisible(true, 'quoteTemVisible');
		this.setState({
			detailRowData: record,
			modalTemRowID: templateID,
			modalTemRowData: {
				...record,
				templateID,
				nationalCatalogueID,
			}
		}, () => {
			this.getElementSelectData('modalTemRowData', 'modalElementTableData');
		})
	}

	// 删除明细
	handleDelete = async record => {
		try {
			let { userData } = this.state;
			let data = {
				params: [{
					hospID: userData?.hospID || '',
					nationAttributeRelevanceID: record?.nationAttributeRelevanceID || '',
				}],
			}
			let res = await React.$asyncPost(this, '06050036', data);
			message.success(res.errorMessage || '删除成功');
			this.getDetailTableData();
		} catch (error) {
			console.log(error)
		}
	}

	/**
	* @ByShizi: 回车过滤元素数据
	* 需求 #1062
	* Create 2023-01-30
	* */
	handleElementInputPressEnter = (e) => {
		let { copyElementSelectData } = this.state;
		let val = e.target.value;
		let elementSelectData = copyElementSelectData && copyElementSelectData.filter(item => item.filterVal.indexOf(val) > -1);
		this.setState({ elementSelectData });
	}

	// 回车过滤模板数据
	handleTemplateInputPressEnter = (e) => {
		let { copyModalTemplateTableData } = this.state;
		let val = e.target.value;
		let modalTemplateTableData = copyModalTemplateTableData && copyModalTemplateTableData.filter(item => item.filterVal.indexOf(val) > -1);
		this.setState({ modalTemplateTableData, modalTemRowID: '', modalElementTableData: [] });
	}

	// 回车过滤元素数据
	handleTemplateElementInputPressEnter = (e) => {
		let { copyModalElementTableData } = this.state;
		let val = e.target.value;
		let modalElementTableData = copyModalElementTableData && copyModalElementTableData.filter(item => item.filterVal.indexOf(val) > -1);
		this.setState({ modalElementTableData });
	}

	render() {
		let { tempValue, mainLoading, mainTableData, mainRowID, mainElementLoading, mainElementTableData, mainElementRowID, detailLoading, detailTableData, selectedRowKeys, selectedRows,
			visible, elementSelectData, modalTemplateTableData, modalElementTableData, quoteTemVisible
		} = this.state;

		let operationObj = {
			width: 130,
			title: '操作',
			// fixed: 'right',
			align: 'center',
			key: 'operation',
			render: (text, record) => (
				<span>
					<Icon type="edit" className="common-record-span-icon"></Icon>
					<span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
					<Divider type="vertical" />
					<Icon type="delete" className="common-record-delete-span"></Icon>
					<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
						<span className="span common-record-delete-span">删除</span>
					</Popconfirm>
				</span>
			),
		};

		let rowSelection = {
			selectedRowKeys,
			selectedRows,
			onChange: this.handleRowSelectionChange,
		};
		return (
			<div className='emr-reference'>
				<Row className="table-body-height">
					<Col span={12}>
						<div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
							<Card
								size="small"
								title={(
									<div className="card-title-left-icon">
										<div></div>
										病历模板
									</div>
								)}
							>
								<Row>
									<Col span={14}>
										<div style={{ marginBottom: 12 }}>
											模板名称：<Input
												placeholder="请输入检索条件"
												title="输入内容后可回车检索"
												value={tempValue}
												style={{ width: '160px', marginRight: '12px' }}
												onPressEnter={this.handleFilterMainTableData}
												onChange={Util.commonInputChange.bind(this, 'tempValue')}
											/>
											<Button onClick={this.handleFilterMainTableData}>查询</Button>
										</div>
										<PubilcTablePagination
											param={{
												loading: mainLoading,
												data: mainTableData, // 表格数据
												columns: this.staticColumns, // 表头配置
												x: 230, // 表格的宽度
												y: store.getState().tableHeight.y + 85,
												height: store.getState().tableHeight.y + 135 + 'px',
											}}
											onClickRowPublic={this.handleMainRowClick}
											setRowClassNamePublic={this.handleMainRowClassName}
										/>
									</Col>
									<Col span={10} style={{ paddingLeft: 12 }}>
										<div style={{ height: '33px', marginBottom: 12, textAlign: 'right' }}>
											<Button
												icon="plus"
												disabled={!mainRowID}
												className={mainRowID ? "add-btn add-btn-nohover" : ''}
												onClick={this.handleAddMainElement}
											>添加元素</Button>
										</div>
										<PubilcTablePagination
											param={{
												loading: mainElementLoading,
												data: mainElementTableData, // 表格数据
												columns: this.staticElementColumns, // 表头配置
												x: 350, // 表格的宽度
												y: store.getState().tableHeight.y + 85,
												height: store.getState().tableHeight.y + 135 + 'px',
											}}
											onClickRowPublic={this.handleMainElementRowClick}
											setRowClassNamePublic={this.handleMainElementRowClassName}
										/>
									</Col>
								</Row>
							</Card>
							<div className="common-card-right-split-line" style={{ width: 6 }}></div>
						</div>
					</Col>
					<Col span={12}>
						<Card
							size="small"
							title={(
								<div className="card-title-left-icon">
									<div></div>
									引用模板
								</div>
							)}
						>
							<div style={{ height: '33px', marginBottom: 12, textAlign: 'right' }}>
								<Button
									icon="plus"
									disabled={!mainElementRowID}
									className={mainElementRowID ? "add-btn add-btn-nohover" : ''}
									onClick={this.handleAddDetailElement}
								>添加引用数据</Button>
							</div>
							<PubilcTablePagination
								param={{
									loading: detailLoading,
									data: detailTableData, // 表格数据
									columns: [...this.staticDetailColumns, operationObj], // 表头配置
									x: 700, // 表格的宽度
									y: store.getState().tableHeight.y + 85,
									height: store.getState().tableHeight.y + 135 + 'px',
								}}
							/>
						</Card>
					</Col>
				</Row>
				<Modal
					width="1000px"
					title="添加病历元素"
					visible={visible}
					destroyOnClose={true}
					onCancel={() => this.modifyVisible(false)}
					onOk={this.handleConfirm}
				>
					<div style={{ marginBottom: '12px', textAlign: 'right' }}>
						<Input
							style={{ width: '300px' }}
							placeholder="输入元素代码/描述/filedID/注解回车查询"
							onPressEnter={this.handleElementInputPressEnter}
						/>
					</div>
					<div className="table-body-height">
						<PubilcTablePagination
							param={{
								x: 800, // 表格的宽度
								y: 450,
								height: 500,
								data: elementSelectData, // 表格数据
								columns: this.staticElementModalColumns, // 表头配置
							}}
							rowSelectionPublic={rowSelection}
						/>
					</div>
				</Modal>
				<Modal
					width="1000px"
					title="添加引用模板"
					visible={quoteTemVisible}
					destroyOnClose={true}
					onCancel={() => this.modifyVisible(false, 'quoteTemVisible')}
					onOk={this.handleQuoteConfirm}
				>
					<Row className="table-body-height">
						<Col span={12}>
							<div style={{ marginBottom: '12px' }}>
								<Input
									style={{ width: '300px' }}
									placeholder="输入模板代码/描述回车查询"
									onPressEnter={this.handleTemplateInputPressEnter}
								/>
							</div>
							<PubilcTablePagination
								param={{
									x: 380, // 表格的宽度
									y: 450,
									height: 500,
									data: modalTemplateTableData, // 表格数据
									columns: this.staticColumns, // 表头配置
								}}
								onClickRowPublic={this.handleModalTemRowClick}
								setRowClassNamePublic={this.handleModalRowClassName}
							/>
						</Col>
						<Col span={12} style={{ paddingLeft: 12 }}>
							<div style={{ marginBottom: '12px' }}>
								<Input
									style={{ width: '300px' }}
									placeholder="输入元素代码/描述/filedID/注解回车查询"
									onPressEnter={this.handleTemplateElementInputPressEnter}
								/>
							</div>
							<PubilcTablePagination
								param={{
									x: 800, // 表格的宽度
									y: 450,
									height: 500,
									data: modalElementTableData, // 表格数据
									columns: this.staticElementModalColumns, // 表头配置
								}}
								onClickRowPublic={this.handleModalElementRowClick}
								setRowClassNamePublic={this.handleModalElementRowClassName}
							/>
						</Col>
					</Row>
				</Modal>
			</div>
		)
	}
};

export default EMRReference;